package com.hjqjl.mvvmdemo.repository;

import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import com.hjqjl.mvvmdemo.db.AppDatabase;
import com.hjqjl.mvvmdemo.db.UserDao;
import com.hjqjl.mvvmdemo.model.User;
import com.hjqjl.mvvmdemo.net.BaseObserver;
import com.hjqjl.mvvmdemo.net.HttpMethods;

import java.util.Random;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 2022/9/13 16:52 wh
 */
public class UserRepository {
    private UserDao userDao;

    public UserRepository() {
        this.userDao = AppDatabase.getInstance().userDao();
    }

    public LiveData<User> getUser(final String name) {
        refresh(name);
        return userDao.getUserByName(name);
    }

    public void refresh(String name) {
        HttpMethods.getInstance().getUser(name)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<User>() {

                    @Override
                    public void onSuccess(User user) {
                        //存储到数据库中
                        user.setCompany("" + new Random().nextInt(1000));
                        insertUser(user);
                    }
                });
    }

    public void insertUser(User user) {
        //开启工作线程，插入数据到数据库
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                userDao.insertUser(user);
            }
        });
    }
}
